<template>
  <!-- <div style="height: 100vh;width: 100vw"> -->
  <el-container>
    <el-main>
      <div ref="viewport" class="viewport">
        <!-- tabindex allows for div to be focused -->
        <!-- <div ref="display" class="display" tabindex="0"/> -->
        <div ref="display" class="display" tabindex="0" style="width: 100%; height: 100%;"/>
      </div>
      <el-dialog
        custom-class="rdp-dialog"
        title=""
        :visible.sync="Successdialog" 
        :show-close= false 
        :close-on-click-modal= true 
        :close-on-press-escape= false
        :modal="false" 
        center>
        <span style="font-size:18px;color:aliceblue;">工一云电脑：{{Sencond}}。</span> 
      </el-dialog>
      <el-dialog
        title=""
        :visible.sync="upLoad"
        width="60%"
        :show-close= false 
        :close-on-click-modal= true 
        :close-on-press-escape= false
        :modal="false" 
      >
        <iframe
          :src="webPageUrl"
          width="100%"
          height="500"
          frameborder="0"
          allowfullscreen
        ></iframe>
        <!-- <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
        </span> -->
      </el-dialog>
      <!-- <div v-if="isMobile">
        <i v-if="isMouseType" class="osk el-icon-s-platform"  @click="changeMouseMode" ></i>
        <i v-else class="osk el-icon-thumb"  @click="changeMouseMode" ></i>
      </div> -->
      <div
        class="osk3"
        draggable="true"
        @dragstart="dragstart($event)"
        @dragend="dragend($event)"
        :style="`left:${elLeft}px;top:${elTop}px;`"
        @dragover="allowDrop($event)"
        @dragenter = "handleOndragenter($event)"
        @click = "handleToolBarClick"
      >
      <el-tooltip class="item" effect="dark" placement="bottom" content="工具栏">
        <el-image
          class="toolbar"
          :src="require('@/assets/favicon.png')" 
          /> 
      </el-tooltip> 
      
        <span  v-if="toolBarActive" class="toolbar" style="font-size:12px;color:aliceblue;align-self: center;">{{serverdelay}}ms</span> 

        <el-image
          v-if="toolBarActive"
          class="toolbar"
          style="width: 23px;"
          :src="require('@/assets/uploadwhile.png')" 
          @click.stop="handleUpload"
          >
        </el-image>
      
      
      
        <el-image
          v-if="toolBarActive"
          class="toolbar"
          style="width: 23px;"
          :src="require('@/assets/fullscreenwhile.png')" 
          @click.stop="handlefullscreen"
        />
      

      <el-image
        v-if="toolBarActive"
        class="toolbar"
        style="width: 21px;height: 25px;"
        :src="require('@/assets/switch_white.png')" 
        @click.stop="handleswitch"
      />

      <el-image
        v-if="toolBarActive && isMouseType && isMobile"
        class="toolbar"
        style="width: 21px;height: 25px;"
        :src="require('@/assets/Mouse.png')" 
        @click.stop="changeMouseMode"
      />

      <el-image
        v-if="toolBarActive && !isMouseType && isMobile"
        class="toolbar"
        style="width: 21px;height: 25px;"
        :src="require('@/assets/mobile-phone.png')" 
        @click.stop="changeMouseMode"
      />

     
      <el-image
        v-if="toolBarActive"
        class="toolbar"
        style="width: 19px;height: 21px; margin-top: 8px;"
        :src="require('@/assets/closewhile.png')"
        @click.stop="handledisconnect"
      />
      </div>
    </el-main>
  </el-container>
  <!-- </div> -->
</template>

<script>
import Guacamole from 'guacamole-common-js'
import GuacMouse from '@/libs/GuacMouse'
import states from '@/libs/states'
import clipboard from '@/libs/clipboard'
import axios from 'axios'
//自定义鼠标
Guacamole.Mouse = GuacMouse.mouse

function serialize (obj) {
  let str = [];
  for (const p in obj)
    if (obj[p]) {
      str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
    }
  return str.join("&");
}
export default {
  name:'GuacClient2',
  components: {
    
  },
  data() {
    return {
      demo:'win',
      connected: false,
      display: null,
      currentAdjustedHeight: null,
      tunnel: null,
      client: null,
      keyboard: null,
      mouse: null,
      lastEvent: null,
      connectionState: states.IDLE,
      errorMessage: '',
      arguments: {},
      query:{
          guacad_addr:'guacd.mojotv.cn:4822',
          // guacad_addr:'127.0.0.1:4822',
          asset_protocol:'rdp',
          asset_host:'wangjing.cec.cc',
          asset_port:'3389',
          asset_user:'wangjing@cec.cc',
          asset_password:'cec-123456wj@',
          screen_width:1024,
          screen_height:768,
          screen_dpi:96,
          GatewayHostname: "ccg.cec.cc",
          GatewayPort: "88",
          GatewayUsername: "wangjing@cec.cc",
          GatewayPassword: "cec-123456wj@",
          vmid: "",
          username: "",
      },

      Successdialog: true,//控制弹出
      Sencond: "认证成功",//设置初始倒计时
      isDisabled: true,
      isMobile: false,
      isMouseType: true,
      upLoad: false,
      webPageUrl: 'https://www.baidu.com',
      initWidth: 0, // 父元素的宽-自适应值
      initHeight: 0, // 父元素的高-自适应值
      startclientX: 0, // 元素拖拽前距离浏览器的X轴位置
      startclientY: 0, //元素拖拽前距离浏览器的Y轴位置
      elLeft: 0, // 元素的左偏移量
      elTop: 0, // 元素的右偏移量
      toolBarActive: false,
      username: "",
      password: "",
      handleshut: false,
      layer: null,
      rdpinit: true,
      xscale: 1,
      yscale: 1,
      serverdelay: 0,
    }
  },
  computed: {

    wsUrl() {
      let loc = window.location, new_uri;
      if (loc.protocol === "https:") {
        new_uri = "wss:";
      } else {
        new_uri = "ws:";
      }
      //new_uri += "//127.0.0.1:9528"
      new_uri += "//" + loc.host;
      new_uri += "/ws";
      return `${new_uri}`
    }
  },
  watch: {
    // connectionState(state) {
    //   this.$notify({
    //     title: state,
    //     type: 'success'
    //   });
    // },
  },
  methods: {
    changeMouseMode(){
      console.log("触摸屏模式切换")
      console.log(this.mouse)
      // 触摸屏鼠标模式切换
      if(this.mouse.mouseModeTouch){
        this.mouse.mouseModeTouch =false;
        this.isMouseType = true;
      }else{
        this.mouse.mouseModeTouch =true;
        this.isMouseType = false;
      }
      console.log("this.display.showCursor true")
      // 控制鼠标图标显示显示
      this.display.showCursor(true);
    },

    sendMsg () {
      window.close()
    },

    getSencond () {
      const that = this
      const interval = window.setInterval(function () {
        // --that.Sencond
        if (that.Sencond === "正在登录") {
          // console.log(that.mouse.State);
          that.Sencond = "点击开始"
          if(!that.isMobile){
            that.Successdialog = false;
            //console.log("that mouse");
            //console.log(that.mouse);
            //const scaledMouseState = Object.assign({}, that.mouse.currentState, {
             // x: that.mouse.currentState.x  / that.display.getScale() + 10,
              //y: that.mouse.currentState.y / that.display.getScale() + 10,
            //})
            //that.client.sendMouseState(scaledMouseState);
            window.clearInterval(interval);
            return;
            }
            //that.mouse.currentState.left =true;
            //that.mouse.onmousedown(that.mouse.currentState);
            that.Sencond = "点击开始"
            setTimeout(()=> {that.Successdialog = false
              //const scaledMouseState = Object.assign({}, that.mouse.currentState, {
                //x: that.mouse.currentState.x  / that.display.getScale() + 20,
                //y: that.mouse.currentState.y / that.display.getScale() + 20,
                //left: true,
                //})
              //that.client.sendMouseState(scaledMouseState);
              //that.mouse.currentState.left =false;
              //that.mouse.onmouseup(that.mouse.currentState);
              //const scaledMouseState1 = Object.assign({}, that.mouse.currentState, {
                //x: that.mouse.currentState.x  / that.display.getScale() + 20,
                //y: that.mouse.currentState.y / that.display.getScale() + 20,
                //left: false,
              //})
              //that.client.sendMouseState(scaledMouseState1);
            }, 1000)
            const displayElm = that.$refs.display
            displayElm.focus();

          window.clearInterval(interval);
          //that.sendMsg()//倒计时结束时运行的业务逻辑，这里的是关闭当前页面
        }
      }, 1000)
    },
    atChangeDemo(v){
      if (v === 'win'){
        this.query = {
          guacad_addr:'guacd.mojotv.cn:4822',
          asset_protocol:'rdp',
          asset_host:'wangjing.cec.cc',
          asset_port:'3389',
          asset_user:'wangjing@cec.cc',
          asset_password:'cec-123456wj@',
          screen_width:1024,
          screen_height:768,
          screen_dpi:128,
          GatewayHostname: "ccg.cec.cc",
          GatewayPort: "88",
          GatewayUsername: "wangjing@cec.cc",
          GatewayPassword: "cec-123456wj@",
        }
        return
      }
      if (v === 'vnc'){
        this.query = {
          guacad_addr:'guacd.mojotv.cn:4822',
          asset_protocol:'vnc',
          asset_host:'guacd-vnc.mojotv.cn',
          asset_port:'5901',
          asset_user:'root',
          asset_password:'vncpassword',
          screen_width:1024,
          screen_height:768,
          screen_dpi:128,
          GatewayHostname: "",
          GatewayPort: "",
          GatewayUsername: "",
          GatewayPassword: "",
        }
        return
      }
      if (v === 'rdp'){
        this.query = {
          guacad_addr:'guacd.mojotv.cn:4822',
          asset_protocol:'rdp',
          asset_host:'wangjing.cec.cc',
          asset_port:'3389',
          asset_user:'wangjing@cec.cc',
          asset_password:'cec-123456wj@',
          screen_width:1024,
          screen_height:768,
          screen_dpi:128,
          GatewayHostname: "ccg.cec.cc",
          GatewayPort: "88",
          GatewayUsername: "wangjing@cec.cc",
          GatewayPassword: "cec-123456wj@",

        }
      }
    },
    doGuacdConnect(){
      this._setScreenSize()
      this.startGuacamole()
    },
    send(cmd) {
      if (!this.client) {
        return
      }
      for (const c of cmd.data) {
        this.client.sendKeyEvent(1, c.charCodeAt(0))
      }
    },
    copy(cmd) {
      if (!this.client) {
        return
      }
      clipboard.cache = {
        type: 'text/plain',
        data: cmd.data
      }
      clipboard.setRemoteClipboard(this.client)
    },
    handleMouseState(mouseState) {
      // console.log(mouseState);
      const scaledMouseState = Object.assign({}, mouseState, {
        //x : mouseState.x / this.display.getScale(),
        x : mouseState.x / this.xscale,
        // y: mouseState.y / this.display.getScale(),
        y: mouseState.y / this.yscale,
      })
      this.client.sendMouseState(scaledMouseState);
    },
    _setScreenSize(){
      console.log("_setScreenSize")
      const elm = this.$refs.viewport
      if (!elm || !elm.offsetWidth) {
        // resize is being called on the hidden window
        return
      }
      // let pixelDensity = window.devicePixelRatio || 1
      // const width = elm.clientWidth * pixelDensity
      // const height = elm.clientHeight * pixelDensity
      // this.query.screen_height = height - 20
      // this.query.screen_width = width - 20
      let pixelDensity = window.devicePixelRatio || 1
      // this.query.screen_width = Math.ceil(elm.clientWidth) 
      //this.query.screen_height = Math.ceil(elm.clientHeight)
      console.log(elm.clientWidth)
      console.log(elm.clientHeight)
      console.log(pixelDensity)
      console.log(this.isMobile)
      // if(elm.clientWidth < 768 && window.devicePixelRatio >1 && this.isMobile){
      if(pixelDensity >1 && this.isMobile){  
        pixelDensity = window.devicePixelRatio || 1
        if(pixelDensity >= 1.5){
           pixelDensity = 1.3
        }
        this.query.screen_width = Math.ceil(elm.clientWidth * pixelDensity) 
        this.query.screen_height = Math.ceil(elm.clientHeight * pixelDensity)
      }else{
        // this.query.screen_width = Math.ceil(elm.clientWidth * pixelDensity) 
        // this.query.screen_height = Math.ceil(elm.clientHeight * pixelDensity)
        this.query.screen_width = elm.clientWidth
        this.query.screen_height = elm.clientHeight
      }
      if(this.isMobile){
        setTimeout(() => {
        
        //   const scale = Math.min(
        //     elm.clientWidth / Math.max(this.display.getWidth(), 1),
        //     elm.clientHeight / Math.max(this.display.getHeight(), 1)
        // )
        //this.display.scale(scale)
        if(this.rdpinit){
          this.display.scale(1)
          this.rdpinit = false
          this.mouse.mouseModeTouch = true;
          this.isMouseType = false
        }
        
        //this.display.scale(scale)
        // this.rdpinit = false
      
    }, 100)
      }
      
      // console.log(this.query.screen_width)
      // console.log(this.query.screen_height)
      // console.log(pixelDensity)
    },

    resize() {
      console.log("resize")
      this._setScreenSize()
      const elm = this.$refs.viewport
      //const elmdisplay = this.$refs.display
      if (!elm || !elm.offsetWidth) {
        // resize is being called on the hidden window
        return
      }
      //let pixelDensity = window.devicePixelRatio || 1
      let pixelDensity = 1
      const width = elm.clientWidth * pixelDensity
      const height = elm.clientHeight * pixelDensity
      if (this.display.getWidth() !== width || this.display.getHeight() !== height) {
        //console.log("sendSize")
        this.client.sendSize(width, height)
        //this.client.autosize = true
        
        
        if(!this.rdpinit){
          //this.handleSize = true

          //this.client.disconnect()
          setTimeout(()=>{
            console.log('匹配分辨率')
            this.Sencond = "匹配分辨率"
            this.handleautosize()
            //let param = serialize(this.query)
            //this.client.connect(param);
          }, 300)
        }
        //this.display.autosize = true
        
      }else{
        if(!this.rdpinit){
          //this.handleSize = true

          //this.client.disconnect()
          setTimeout(()=>{
            console.log('匹配分辨率')
            this.Sencond = "匹配分辨率"
            this.handleautosize()
            //let param = serialize(this.query)
            //this.client.connect(param);
          }, 300)
        }
      }
      // setting timeout so display has time to get the correct size
      setTimeout(() => {
        
          //   const scale = Math.min(
          //     elm.clientWidth / Math.max(this.display.getWidth(), 1),
          //     elm.clientHeight / Math.max(this.display.getHeight(), 1)
          // )
          //this.display.scale(scale)
          if(this.rdpinit){
            this.display.scale(1)
            this.rdpinit = false
          }
          
          //this.display.scale(scale)
          // this.rdpinit = false
        
      }, 100)
    },
    startGuacamole() {
      //this.layer = new Guacamole.Layer(this.query.screen_width, this.query.screen_height)
      //this.layer.autosize = true
      // GuacadAddr    string `form:"guacad_addr"`
      // AssetProtocol string `form:"asset_protocol"`
      // AssetHost     string `form:"asset_host"`
      // AssetPort     string `form:"asset_port"`
      // AssetUser     string `form:"asset_user"`
      // AssetPassword string `form:"asset_password"`
      // ScreenWidth   int    `form:"screen_width"`
      // ScreenHeight  int    `form:"screen_height"`
      // ScreenDpi     int    `form:"screen_dpi"`
      
        
      var tunnel = new Guacamole.WebSocketTunnel(this.wsUrl)
      
      if (this.client) {
        this.display.scale(0)
        this.uninstallKeyboard()
      }

      this.client = new Guacamole.Client(tunnel);
      clipboard.install(this.client)

      tunnel.onerror = status => {
        // eslint-disable-next-line no-console
        console.error(`Tunnel failed ${JSON.stringify(status)}`)
        this.connectionState = states.TUNNEL_ERROR
      }

      tunnel.onstatechange = state => {
        switch (state) {
            // Connection is being established
          case Guacamole.Tunnel.State.CONNECTING:
            this.connectionState = states.CONNECTING
            this.Sencond = "正在连接"
            break;

            // Connection is established / no longer unstable
          case Guacamole.Tunnel.State.OPEN:
            this.connectionState = states.CONNECTED
            break;

            // Connection is established but misbehaving
          case Guacamole.Tunnel.State.UNSTABLE:
            // TODO
              //this.$message.error("不稳定")
            break;

            // Connection has closed
          case Guacamole.Tunnel.State.CLOSED:
            this.connectionState = states.DISCONNECTED
            // 添加页面返回,清空user_uuid
            //this.tunnel.disconnect();
            if(!this.handleshut && !this.handleSize){
              console.log("!this.handleshut && !this.handleSize")
              sessionStorage.removeItem("user_uuid")
              sessionStorage.removeItem('cc_vmid')
              sessionStorage.removeItem('asset_protocol')
              sessionStorage.removeItem('asset_host')
              sessionStorage.removeItem('username')
              sessionStorage.removeItem('password')
              sessionStorage.removeItem('ccList')
              sessionStorage.removeItem('index')
              this.$router.go(0)
            }else if(this.handleSize){
              console.log("this.handleSize")
              // let param = serialize(this.query)
              // this.client.connect(param);
              // this.handleSize = false
            }
            break;
        }
      }

      this.client.onstatechange = clientState => {
        switch (clientState) {
          case 0:
            this.connectionState = states.IDLE
            break
          case 1:
            // connecting ignored for some reason?
            break
          case 2:
            this.connectionState = states.WAITING
            break
          case 3:
            this.connectionState = states.CONNECTED
            window.addEventListener('resize', this.resize)
            this.$refs.viewport.addEventListener('mouseenter', this.resize)

            clipboard.setRemoteClipboard(this.client)
            // 立即显示画面
            this.Sencond = "正在登录"
            // 

            // eslint-disable-next-line no-fallthrough
          case 4:
          case 5:
            // disconnected, disconnecting
            break
        }
      }

      this.client.onerror = error => {
        this.client.disconnect()
        // eslint-disable-next-line no-console
        //this.$message.error(`Client error ${JSON.stringify(error)}`)
        this.errorMessage = error.message
        this.connectionState = states.CLIENT_ERROR
      }

      this.client.onsync = () => {
      }

      this.client.onresize = (width, height) => {
        console.log("client onresize")
        console.log(width)
        console.log(height)
      }

      // Test for argument mutability whenever an argument value is received
      this.client.onargv = (stream, mimetype, name) => {
        if (mimetype !== 'text/plain')
          return;

        const reader = new Guacamole.StringReader(stream);

        // Assemble received data into a single string
        let value = '';
        reader.ontext = text => {
          value += text;
        };

        // Test mutability once stream is finished, storing the current value for the argument only if it is mutable
        reader.onend = () => {
          const stream = this.client.createArgumentValueStream('text/plain', name)
          stream.onack = status => {
            if (status.isError()) {
              // ignore reject
              return
            }
            this.arguments[name] = value
          }
        };
      }

      this.client.onclipboard = clipboard.onClipboard
      this.display = this.client.getDisplay()
      const displayElm = this.$refs.display
      displayElm.appendChild(this.display.getElement());
      displayElm.addEventListener('contextmenu', e => {
        e.stopPropagation();
        if (e.preventDefault) {
          e.preventDefault();
        }
        e.returnValue = false;
      })

      let param = serialize(this.query)
      this.client.connect(param);
      window.onunload = () => this.client.disconnect();
      // 开始挂载鼠标
      this.mouse = new Guacamole.Mouse(displayElm);
      //添加鼠标模式状态
      this.mouse.isMobile = this.isMobile;
      //this.mouse.isMobile = false;
      //this.mouse.mouseModeTouch = false;
      // Hide software cursor when mouse leaves display
      this.mouse.onmouseout = () => {
        if (!this.display) return;
        console.log("this.display.showCursor false")
        this.display.showCursor(false);
      }

      // allows focusing on the display div so that keyboard doesn't always go to session
      displayElm.onclick = () => {
        displayElm.focus()
      }
      displayElm.onfocus = () => {
        displayElm.className = 'focus'
      }
      displayElm.onblur = () => {
        displayElm.className = ''
      }
      //挂载处理键盘
      if(!this.isMobile){
        console.log("keyboard")
        this.keyboard = new Guacamole.Keyboard(displayElm);
        this.installKeyboard()
      }
      else{
        this.keyboard = new Guacamole.Keyboard(displayElm);
        this.installKeyboard()
      }
      //else{
        //虚拟键盘数据
        //var a =   {"language":"en_US","type":"qwerty","width":22,"keys":{"0":[{"title":"0","requires":[]},{"title":")","requires":["shift"]}],"1":[{"title":"1","requires":[]},{"title":"!","requires":["shift"]}],"2":[{"title":"2","requires":[]},{"title":"@","requires":["shift"]}],"3":[{"title":"3","requires":[]},{"title":"#","requires":["shift"]}],"4":[{"title":"4","requires":[]},{"title":"$","requires":["shift"]}],"5":[{"title":"5","requires":[]},{"title":"%","requires":["shift"]}],"6":[{"title":"6","requires":[]},{"title":"^","requires":["shift"]}],"7":[{"title":"7","requires":[]},{"title":"&","requires":["shift"]}],"8":[{"title":"8","requires":[]},{"title":"*","requires":["shift"]}],"9":[{"title":"9","requires":[]},{"title":"(","requires":["shift"]}],"Back":65288,"Tab":65289,"Enter":65293,"Esc":65307,"Home":65360,"PgUp":65365,"PgDn":65366,"End":65367,"Ins":65379,"F1":65470,"F2":65471,"F3":65472,"F4":65473,"F5":65474,"F6":65475,"F7":65476,"F8":65477,"F9":65478,"F10":65479,"F11":65480,"F12":65481,"Del":65535,"Space":" ","Left":[{"title":"←","keysym":65361}],"Up":[{"title":"↑","keysym":65362}],"Right":[{"title":"→","keysym":65363}],"Down":[{"title":"↓","keysym":65364}],"Menu":[{"title":"Menu","keysym":65383}],"LShift":[{"title":"Shift","modifier":"shift","keysym":65505}],"RShift":[{"title":"Shift","modifier":"shift","keysym":65506}],"LCtrl":[{"title":"Ctrl","modifier":"control","keysym":65507}],"RCtrl":[{"title":"Ctrl","modifier":"control","keysym":65508}],"Caps":[{"title":"Caps","modifier":"caps","keysym":65509}],"LAlt":[{"title":"Alt","modifier":"alt","keysym":65513}],"RAlt":[{"title":"Alt","modifier":"alt","keysym":65514}],"Super":[{"title":"Super","modifier":"super","keysym":65515}],"`":[{"title":"`","requires":[]},{"title":"~","requires":["shift"]}],"-":[{"title":"-","requires":[]},{"title":"_","requires":["shift"]}],"=":[{"title":"=","requires":[]},{"title":"+","requires":["shift"]}],",":[{"title":",","requires":[]},{"title":"<","requires":["shift"]}],".":[{"title":".","requires":[]},{"title":">","requires":["shift"]}],"/":[{"title":"/","requires":[]},{"title":"?","requires":["shift"]}],"[":[{"title":"[","requires":[]},{"title":"{","requires":["shift"]}],"]":[{"title":"]","requires":[]},{"title":"}","requires":["shift"]}],"\\":[{"title":"\\","requires":[]},{"title":"|","requires":["shift"]}],";":[{"title":";","requires":[]},{"title":":","requires":["shift"]}],"'":[{"title":"'","requires":[]},{"title":"\"","requires":["shift"]}],"q":[{"title":"q","requires":[]},{"title":"Q","requires":["caps"]},{"title":"Q","requires":["shift"]},{"title":"q","requires":["caps","shift"]}],"w":[{"title":"w","requires":[]},{"title":"W","requires":["caps"]},{"title":"W","requires":["shift"]},{"title":"w","requires":["caps","shift"]}],"e":[{"title":"e","requires":[]},{"title":"E","requires":["caps"]},{"title":"E","requires":["shift"]},{"title":"e","requires":["caps","shift"]}],"r":[{"title":"r","requires":[]},{"title":"R","requires":["caps"]},{"title":"R","requires":["shift"]},{"title":"r","requires":["caps","shift"]}],"t":[{"title":"t","requires":[]},{"title":"T","requires":["caps"]},{"title":"T","requires":["shift"]},{"title":"t","requires":["caps","shift"]}],"y":[{"title":"y","requires":[]},{"title":"Y","requires":["caps"]},{"title":"Y","requires":["shift"]},{"title":"y","requires":["caps","shift"]}],"u":[{"title":"u","requires":[]},{"title":"U","requires":["caps"]},{"title":"U","requires":["shift"]},{"title":"u","requires":["caps","shift"]}],"i":[{"title":"i","requires":[]},{"title":"I","requires":["caps"]},{"title":"I","requires":["shift"]},{"title":"i","requires":["caps","shift"]}],"o":[{"title":"o","requires":[]},{"title":"O","requires":["caps"]},{"title":"O","requires":["shift"]},{"title":"o","requires":["caps","shift"]}],"p":[{"title":"p","requires":[]},{"title":"P","requires":["caps"]},{"title":"P","requires":["shift"]},{"title":"p","requires":["caps","shift"]}],"a":[{"title":"a","requires":[]},{"title":"A","requires":["caps"]},{"title":"A","requires":["shift"]},{"title":"a","requires":["caps","shift"]}],"s":[{"title":"s","requires":[]},{"title":"S","requires":["caps"]},{"title":"S","requires":["shift"]},{"title":"s","requires":["caps","shift"]}],"d":[{"title":"d","requires":[]},{"title":"D","requires":["caps"]},{"title":"D","requires":["shift"]},{"title":"d","requires":["caps","shift"]}],"f":[{"title":"f","requires":[]},{"title":"F","requires":["caps"]},{"title":"F","requires":["shift"]},{"title":"f","requires":["caps","shift"]}],"g":[{"title":"g","requires":[]},{"title":"G","requires":["caps"]},{"title":"G","requires":["shift"]},{"title":"g","requires":["caps","shift"]}],"h":[{"title":"h","requires":[]},{"title":"H","requires":["caps"]},{"title":"H","requires":["shift"]},{"title":"h","requires":["caps","shift"]}],"j":[{"title":"j","requires":[]},{"title":"J","requires":["caps"]},{"title":"J","requires":["shift"]},{"title":"j","requires":["caps","shift"]}],"k":[{"title":"k","requires":[]},{"title":"K","requires":["caps"]},{"title":"K","requires":["shift"]},{"title":"k","requires":["caps","shift"]}],"l":[{"title":"l","requires":[]},{"title":"L","requires":["caps"]},{"title":"L","requires":["shift"]},{"title":"l","requires":["caps","shift"]}],"z":[{"title":"z","requires":[]},{"title":"Z","requires":["caps"]},{"title":"Z","requires":["shift"]},{"title":"z","requires":["caps","shift"]}],"x":[{"title":"x","requires":[]},{"title":"X","requires":["caps"]},{"title":"X","requires":["shift"]},{"title":"x","requires":["caps","shift"]}],"c":[{"title":"c","requires":[]},{"title":"C","requires":["caps"]},{"title":"C","requires":["shift"]},{"title":"c","requires":["caps","shift"]}],"v":[{"title":"v","requires":[]},{"title":"V","requires":["caps"]},{"title":"V","requires":["shift"]},{"title":"v","requires":["caps","shift"]}],"b":[{"title":"b","requires":[]},{"title":"B","requires":["caps"]},{"title":"B","requires":["shift"]},{"title":"b","requires":["caps","shift"]}],"n":[{"title":"n","requires":[]},{"title":"N","requires":["caps"]},{"title":"N","requires":["shift"]},{"title":"n","requires":["caps","shift"]}],"m":[{"title":"m","requires":[]},{"title":"M","requires":["caps"]},{"title":"M","requires":["shift"]},{"title":"m","requires":["caps","shift"]}]},"layout":[{"main":{"alpha":[["Esc",0.7,"F1","F2","F3","F4",0.7,"F5","F6","F7","F8",0.7,"F9","F10","F11","F12"],["`","1","2","3","4","5","6","7","8","9","0","-","=","Back"],["Tab","q","w","e","r","t","y","u","i","o","p","[","]","\\"],["Caps","a","s","d","f","g","h","j","k","l",";","'","Enter"],["LShift","z","x","c","v","b","n","m",",",".","/","RShift"],["LCtrl","Super","LAlt","Space","RAlt","Menu","RCtrl"]]}}]};
        //this.keyboard = new Guacamole.OnScreenKeyboard(a);
        //document.getElementById('osk').appendChild(this.keyboard .getElement());
        //this.installKeyboard();
      //}
      
      this.mouse.onmousedown = this.mouse.onmouseup = this.mouse.onmousemove = this.handleMouseState
      setTimeout(() => {
        // this.resize()
        displayElm.focus()
      }, 1000); // $nextTick wasn't enough
    },
    installKeyboard() {
      this.keyboard.onkeydown = keysym => {
        this.client.sendKeyEvent(1, keysym);
      };
      this.keyboard.onkeyup = keysym => {
        this.client.sendKeyEvent(0, keysym);
      };
    },
    uninstallKeyboard() {
      this.keyboard.onkeydown = this.keyboard.onkeyup = () => {
      }
    },

    objToParams(obj) {
        let arr = [];
        for (let key in obj) {
            arr.push(`${key}=${obj[key]}`);
        }
            return arr.join('&');
        },
    

     checkMobile() {
        //this.isMobile = window.innerWidth <= 767;
        //console.log(this.isMobile) 
        if('ontouchstart' in window || navigator.maxTouchPoints){
          this.isMobile = true;
        }
        else{
          this.isMobile = false;
        }
        console.log("isMobile", this.isMobile);
        
        //return this.isMobile;
      },

      handleUpload(){
        this.upLoad = true;
        console.log(this.webPageUrl)
      },

      // 页面初始化
    initBodySize() {
      const elm = this.$refs.viewport
      if(this.isMobile && elm.clientWidth > 768){
        this.initWidth = this.$refs.viewport.clientWidth; // 拿到父元素宽
        // this.initHeight = this.initWidth * (1080 / 1920);
        this.initHeight = this.initWidth * ((1080 * 0.88) / (1920 - 1080 * 0.02)); // 根据宽计算高实现自适应
        this.elLeft = Math.ceil(this.initWidth * 0.7)
      }
      else{
        this.initWidth = this.$refs.viewport.clientWidth; // 拿到父元素宽
        // this.initHeight = this.initWidth * (1080 / 1920);
        this.initHeight = this.initWidth * ((1080 * 0.88) / (1920 - 1080 * 0.02)); // 根据宽计算高实现自适应
        this.elLeft = Math.ceil(this.initWidth * 0.4)
      }
      
    },
    // 拖拽开始事件
    dragstart(e) {
      //e.preventDefault();
      console.log(e);
      this.startclientX = e.clientX; // 记录拖拽元素初始位置
      this.startclientY = e.clientY;
      
      
    },
    // 拖拽完成事件
    dragend(e) {
      e.preventDefault();
      console.log(e);
      let x = e.clientX - this.startclientX; // 计算偏移量
      let y = e.clientY - this.startclientY;
      this.elLeft += x; // 实现拖拽元素随偏移量移动
      this.elTop += y;
      
    },
    //消除移动时的禁止标志
    allowDrop (e) {
      e.preventDefault();
    },

    imageMouseMove(e){
      e.preventDefault();
    },

    handleOndragenter(e){
      console.log(e);
      e.preventDefault();
    },

    handleToolBarClick(){
      this.toolBarActive = !this.toolBarActive
    },

    handlefullscreen(){
      if (!document.fullscreenElement) {
        this.enterFullScreen();
      } else {
        this.exitFullScreen();
      }
    },

    enterFullScreen() {
      let element = document.documentElement;
      if (element.requestFullscreen) {
        element.requestFullscreen();
      } else if (element.mozRequestFullScreen) { /* Firefox */
        element.mozRequestFullScreen();
      } else if (element.webkitRequestFullscreen) { /* Chrome, Safari & Opera */
        element.webkitRequestFullscreen();
      } else if (element.msRequestFullscreen) { /* IE/Edge */
        element.msRequestFullscreen();
      }
    },
    exitFullScreen() {
      if (document.exitFullscreen) {
        document.exitFullscreen();
      } else if (document.mozCancelFullScreen) { /* Firefox */
        document.mozCancelFullScreen();
      } else if (document.webkitExitFullscreen) { /* Chrome, Safari and Opera */
        document.webkitExitFullscreen();
      } else if (document.msExitFullscreen) { /* IE/Edge */
        document.msExitFullscreen();
      }
    },

    handledisconnect(){
      this.handleshut = true
      this.client.disconnect()
      sessionStorage.removeItem("user_uuid")
      sessionStorage.removeItem('cc_vmid')
      sessionStorage.removeItem('asset_protocol')
      sessionStorage.removeItem('asset_host')
      sessionStorage.removeItem('username')
      sessionStorage.removeItem('password')
      sessionStorage.removeItem('ccList')
      sessionStorage.removeItem('index')
      this.$router.go(0)
    },

    handleswitch(){
      this.handleshut = true
      console.log("handleswitch")
      this.$router.push({ path: "/", query: { username: this.username, password: this.password } });
    },

    handleautosize(){
        //this.handleshut = true
        //this.client.disconnect()
        //console.log("handleautosize")
        setTimeout(()=>{
          // this.$router.push({ path: "/", query: { username: this.username, password: this.password, cc_vmid: this.query.vmid} });
          // 回退到上一页
          //this.$router.go(0);
          //console.log(this.display.getElement())
          //var spanChildren = this.display.getElement().querySelector('div')
          var spanChildren = this.display.getElement().childNodes[0]
          //console.log(spanChildren)
          const elm = this.$refs.viewport
          // let pixelDensity = window.devicePixelRatio || 1
          let pixelDensity = 1
          const width = elm.clientWidth * pixelDensity
          const height = elm.clientHeight * pixelDensity
          //console.log(width)
          //console.log(height)
          //console.log(this.display.getWidth())
          //console.log(this.display.getHeight())
          this.xscale = width / this.display.getWidth()
          this.yscale = height / this.display.getHeight()
          //console.log(this.xscale)
          //console.log(this.yscale)
          spanChildren.style.transform = `scale(${this.xscale}, ${this.yscale})`
        }, 100)
        
      },

      getServerDelay(){
        this.getDelay()
        setInterval(() => {
          this.getDelay()
        }, 60000);
      },

      getDelay(){
        const startTime = new Date().getTime();
          axios({
              url: "/api/getserverdelay",
              method: "post",
              headers: {
                  'Content-Type':'application/x-www-form-urlencoded',
              },
              // data: this.objToParams({"vmid": index, "manager_server": manager_server})
          }).then(response => {
            console.log(response.data)
            const endTime = new Date().getTime();
            this.serverdelay = endTime - startTime;
            // console.log(`服务器延迟: ${delay} 毫秒`);
                  })
      }
  },

  mounted() {
     this.getServerDelay()
     this.handleshut = false
     this.username = sessionStorage.getItem("username")
     this.password = sessionStorage.getItem("password")
     let user_uuid= sessionStorage.getItem('user_uuid')
     let manager_server= sessionStorage.getItem('manager_server')
     let asset_protocol = sessionStorage.getItem('asset_protocol')
     let asset_host =  sessionStorage.getItem('asset_host')
     if(asset_protocol == undefined){
      this.query.manager_server = manager_server
      console.log(user_uuid)
      this.query.user_uuid = user_uuid
      this.query.vmid = sessionStorage.getItem('cc_vmid')
      this.query.username = sessionStorage.getItem('username')
      // this.webPageUrl = "http://gw.cec.cc:9528/#/?cecip=" + this.query.vmid + "&cecusername=" + this.query.username
      console.log(this.webPageUrl)
     }
     else if (asset_protocol == 'vnc'){
      this.query.manager_server = manager_server
      this.query.user_uuid = user_uuid
      this.query.vmid = sessionStorage.getItem('cc_vmid')
      this.query.asset_protocol = asset_protocol
      this.query.asset_host = asset_host

     }
     //console.log(this.query)
     this.checkMobile(); //初始化时进行判断是否是移动设备 
     this._setScreenSize()
     let index = sessionStorage.getItem('index');
     console.log(index)
     //console.log(ccList[index])
     if(index != null){
      index = parseInt(sessionStorage.getItem('index'));
      axios({
                  url: "/api/vminfo",
                  method: "post",
                  headers: {
                      'Content-Type':'application/x-www-form-urlencoded',
                  },
                  data: this.objToParams({"vmid": index, "manager_server": manager_server})
              }).then(response => {
                      console.log(response)
                      if(response.status){
                        //   this.$message({
                        //   message: '获取信息成功',
                        //   type: 'success'
                        // });
                        console.log(response.data)
                        if(response.data == "running"){
                            this.startGuacamole()
                            this.getSencond ()
                            this.initBodySize();
                        }
                        else{
                          this.Sencond = "正在开机"
                          // 待添加开机逻辑
                          axios({
                              url: "/api/vmstart",
                              method: "post",
                              headers: {
                                  'Content-Type':'application/x-www-form-urlencoded',
                              },
                              data: this.objToParams({"vmid": index, "manager_server": manager_server})
                          }).then(response => {
                            console.log(response.data)
                            
                            setTimeout(()=>{
                              // this.Sencond == "正在登录"
                              this.startGuacamole()
                              this.getSencond ()
                              this.initBodySize();
                            }, 60000)
                                    })
                          
                        //this.webPageUrl = response.data.data + "/#/?cecip=" + this.query.vmid + "&cecusername=" + this.query.username
                        // console.log(this.webPageUrl)
                      }
                    }
                      else{
                        this.$message({
                          message: '获取云电脑状态失败',
                          type: 'fail'
                        });
                      }
                  }
              ).catch(error => {
                      console.log(456)
                      console.log(error)
                  }
              );
      
    }
     else{
        this.startGuacamole()
        this.getSencond ()
        this.initBodySize();
     }
     axios({
                url: "/api/getrdpwebsite",
                method: "post",
                headers: {
                    'Content-Type':'application/x-www-form-urlencoded',
                },
                data: this.objToParams({"username": this.query.username, "manager_server": manager_server})
            }).then(response => {
                    // console.log(response)
                    // console.log(response.data.status)
                    if(response.data.status){
                      //   this.$message({
                      //   message: '获取信息成功',
                      //   type: 'success'
                      // });
                      // console.log(response.data.data)
                      this.webPageUrl = response.data.data + "/#/?cecip=" + this.query.vmid + "&cecusername=" + this.query.username
                      // console.log(this.webPageUrl)
                    }
                    else{
                      this.$message({
                        message: '获取信息失败',
                        type: 'fail'
                      });
                    }
                }
            ).catch(error => {
                    console.log(456)
                    console.log(error)
                }
            );

  },

  beforeUnmount() {
    this.client.CLOSED();
  },

  

}
</script>

<style scoped>
.el-container{
  width: 100vw;
  height: 100vh;
  padding: 0px;
  margin: -8px;
}
.el-main{
 
  padding: 0px;
  margin: 0px;
}
.display {
  /* overflow: hidden; */
  width: 100%;
  height: 100%;
}

.viewport {
  background-color: rgba(38,92,178,1);
  background-image:  url('~@/assets/2.png');
  background-size:cover;
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
  margin: 0px;
  display: flex;
  justify-content: center;
  align-items: center;
}
 ::v-deep .el-dialog {
  background: rgba(0, 0, 0, 0);
    -webkit-box-shadow: 0 1px 3px rgba(0, 0, 0, 0);
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0);
    opacity: 0.9;
  width: 18%;
}


.osk {
    position: absolute;
    top: 6%;
    color: white;
    left: 50%;
    transform: translate(-50%, -50%);
   
    .guac-keyboard {
    display: inline-block;
    width: 100%;
    
    margin: 0;
    padding: 0;
    cursor: default;
 
    text-align: left;
    vertical-align: middle;
}



 
.guac-keyboard,
.guac-keyboard * {
    overflow: hidden;
    white-space: nowrap;
}
 
.guac-keyboard .guac-keyboard-key-container {
    display: inline-block;
    margin: 0.05em;
    position: relative;
}
 
.guac-keyboard .guac-keyboard-key {
 
    position: absolute;
    left:   0;
    right:  0;
    top:    0;
    bottom: 0;
 
    background: #444;
 
    border: 0.125em solid #666;
    -moz-border-radius:    0.25em;
    -webkit-border-radius: 0.25em;
    -khtml-border-radius:  0.25em;
    border-radius:         0.25em;
 
    color: white;
    font-size: 40%;
    font-weight: lighter;
    text-align: center;
    white-space: pre;
 
    text-shadow:  1px  1px 0 rgba(0, 0, 0, 0.25),
                  1px -1px 0 rgba(0, 0, 0, 0.25),
                 -1px  1px 0 rgba(0, 0, 0, 0.25),
                 -1px -1px 0 rgba(0, 0, 0, 0.25);
 
}
 
.guac-keyboard .guac-keyboard-key:hover {
    cursor: pointer;
}
 
.guac-keyboard .guac-keyboard-key.highlight {
    background: #666;
    border-color: #666;
}
 
/* Align some keys to the left */
.guac-keyboard .guac-keyboard-key-caps,
.guac-keyboard .guac-keyboard-key-enter,
.guac-keyboard .guac-keyboard-key-tab,
.guac-keyboard .guac-keyboard-key-lalt,
.guac-keyboard .guac-keyboard-key-ralt,
.guac-keyboard .guac-keyboard-key-alt-gr,
.guac-keyboard .guac-keyboard-key-lctrl,
.guac-keyboard .guac-keyboard-key-rctrl,
.guac-keyboard .guac-keyboard-key-lshift,
.guac-keyboard .guac-keyboard-key-rshift {
    text-align: left;
    padding-left: 0.75em;
}
 
/* Active shift */
.guac-keyboard.guac-keyboard-modifier-shift .guac-keyboard-key-rshift,
.guac-keyboard.guac-keyboard-modifier-shift .guac-keyboard-key-lshift,
 
/* Active ctrl */
.guac-keyboard.guac-keyboard-modifier-control .guac-keyboard-key-rctrl,
.guac-keyboard.guac-keyboard-modifier-control .guac-keyboard-key-lctrl,
 
/* Active alt */
.guac-keyboard.guac-keyboard-modifier-alt .guac-keyboard-key-ralt,
.guac-keyboard.guac-keyboard-modifier-alt .guac-keyboard-key-lalt,
 
/* Active alt-gr */
.guac-keyboard.guac-keyboard-modifier-alt-gr .guac-keyboard-key-alt-gr,
 
/* Active caps */
.guac-keyboard.guac-keyboard-modifier-caps .guac-keyboard-key-caps,
 
/* Active super */
.guac-keyboard.guac-keyboard-modifier-super .guac-keyboard-key-super {
    background: #882;
    border-color: #DD4;
}
 
.guac-keyboard .guac-keyboard-key.guac-keyboard-pressed {
    background: #822;
    border-color: #D44;
}
 
.guac-keyboard .guac-keyboard-group {
    /* line-height: 0; */
    display: flex;
    justify-content: space-around;
    margin: 10px;
    width: 100%;
}
 
.guac-keyboard .guac-keyboard-group.guac-keyboard-alpha,
.guac-keyboard .guac-keyboard-group.guac-keyboard-movement {
    display: inline-block;
    text-align: center;
    vertical-align: top;
}
 
.guac-keyboard .guac-keyboard-group.guac-keyboard-main {
 
    /* IE10 */
    display: -ms-flexbox;
    -ms-flex-align: stretch;
    -ms-flex-direction: row;
 
    /* Ancient Mozilla */
    display: -moz-box;
    -moz-box-align: stretch;
    -moz-box-orient: horizontal;
    
    /* Ancient WebKit */
    display: -webkit-box;
    -webkit-box-align: stretch;
    -webkit-box-orient: horizontal;
 
    /* Old WebKit */
    display: -webkit-flex;
    -webkit-align-items: stretch;
    -webkit-flex-direction: row;
 
    /* W3C */
    display: flex;
    align-items: stretch;
    flex-direction: row;
 
}
 
.guac-keyboard .guac-keyboard-group.guac-keyboard-movement {
    -ms-flex: 1 1 auto;
    -moz-box-flex: 1;
    -webkit-box-flex: 1;
    -webkit-flex: 1 1 auto;
    flex: 1 1 auto;
}
 
.guac-keyboard .guac-keyboard-gap {
    display: inline-block;
}
 
/* Hide keycaps requiring modifiers which are NOT currently active. */
.guac-keyboard:not(.guac-keyboard-modifier-caps)
.guac-keyboard-cap.guac-keyboard-requires-caps,
 
.guac-keyboard:not(.guac-keyboard-modifier-shift)
.guac-keyboard-cap.guac-keyboard-requires-shift,
 
.guac-keyboard:not(.guac-keyboard-modifier-alt-gr)
.guac-keyboard-cap.guac-keyboard-requires-alt-gr,
 
/* Hide keycaps NOT requiring modifiers which ARE currently active, where that
   modifier is used to determine which cap is displayed for the current key. */
.guac-keyboard.guac-keyboard-modifier-shift
.guac-keyboard-key.guac-keyboard-uses-shift
.guac-keyboard-cap:not(.guac-keyboard-requires-shift),
 
.guac-keyboard.guac-keyboard-modifier-caps
.guac-keyboard-key.guac-keyboard-uses-caps
.guac-keyboard-cap:not(.guac-keyboard-requires-caps),
 
.guac-keyboard.guac-keyboard-modifier-alt-gr
.guac-keyboard-key.guac-keyboard-uses-alt-gr
.guac-keyboard-cap:not(.guac-keyboard-requires-alt-gr) {
 
    display: none;
    
}
 
/* Fade out keys which do not use AltGr if AltGr is active */
.guac-keyboard.guac-keyboard-modifier-alt-gr
.guac-keyboard-key:not(.guac-keyboard-uses-alt-gr):not(.guac-keyboard-key-alt-gr) {
    opacity: 0.5;}
    
  .guac-keyboard-key-container{
    display: flex;
    width: 18px;
    height: 18px;
  }
}

.osk2 {
    position: absolute;
    top: 12%;
    color: white;
    left: 50%;
    transform: translate(-50%, -50%);
}

.osk3 {
    position: absolute;
    top: 0%;
    background-color: rgb(35, 122, 193);
    left: 40%;
    /* transform: translate(-50%, -50%); */
    width: auto;
    cursor: pointer; /* 更改鼠标样式 */
    user-select: none; /* 防止拖拽时选中文本 */
    display: flex;
    border-radius: 5px;
}

.toolbar {
    /* transform: translate(-50%, -50%); */
    width: 25px;
    cursor: pointer; /* 更改鼠标样式 */
    user-select: none; /* 防止拖拽时选中文本 */
    margin: 6px;
}


</style>
